package a01_数组;

/**
 * <p>
 * a05_螺旋矩阵2
 * </p>
 *
 * @author flyduck
 * @since 2024-06-13
 */
public class a06_螺旋矩阵2 {

    public static void main(String[] args) {
        int[][] result = generateMatrix(2);
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result[i].length; j++) {
                System.out.print(result[i][j]+" ");
            }
            System.out.println();
        }
    }

    public static int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        String direction = "right";
        int x = 0;
        int y = 0;
        result[x][y] = 1;
        int value = 1;
        value++;//将要赋值的元素
        while (value <= n * n) {
            if("right".equals(direction)){
                //判断下面要赋值的地方存在不
                if(y + 1 < n && result[x][y + 1] == 0){//可以赋值
                    result[x][y + 1] = value;
                    y++;
                    value++;
                }else {
                    direction = "down";
                }
            }
            if("down".equals(direction)){
                //判断下面要赋值的地方存在不
                if(x + 1 < n && result[x + 1][y] == 0){//可以赋值
                    result[x + 1][y] = value;
                    x++;
                    value++;
                }else {
                    direction = "left";
                }
            }
            if("left".equals(direction)){
                //判断下面要赋值的地方存在不
                if(y - 1 >= 0 && result[x][y - 1] == 0){//可以赋值
                    result[x][y - 1] = value;
                    y--;
                    value++;
                }else {
                    direction = "up";
                }
            }

            if("up".equals(direction)){
                //判断下面要赋值的地方存在不
                if(x - 1 >= 0 && result[x - 1][y] == 0){//可以赋值
                    result[x - 1][y] = value;
                    x--;
                    value++;
                }else {
                    direction = "right";
                }
            }
        }
        return result;
    }
}
